package com.example.suuu.tools.excel.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.example.suuu.model.GenderEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@Slf4j
public class SuUserWriteHandler implements SheetWriteHandler {

    private List<Map<String, String>> paramMap = null;

    public SuUserWriteHandler(List<Map<String, String>> paramMap) {
        this.paramMap = paramMap;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        //性别
        Map<String, String> userSexMap = paramMap.get(0);
        //过滤key为-1的值
        Map<String, String> newUserSexMap = userSexMap.entrySet().stream().filter(map -> ObjectUtil.notEqual(GenderEnum.convert(-1), map.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //名称转成数组
        List<String> userSexList = newUserSexMap.values().stream().collect(Collectors.toList());
        String[] userSex = userSexList.toArray(new String[userSexList.size()]);


        Map<Integer,String[]> mapDropDown = new HashMap<>();
        mapDropDown.put(6,userSex); //性别


        Sheet sheet = writeSheetHolder.getSheet();

        //设置下拉框
        DataValidationHelper helper = sheet.getDataValidationHelper();

        mapDropDown.forEach((k, v) -> {
            // 下拉列表约束数据
            DataValidationConstraint constraint = helper.createExplicitListConstraint(v);
            // 设置下拉单元格的首行 末行 首列 末列
            CellRangeAddressList rangeList = new CellRangeAddressList(2, 65536, k, k);
            // 设置约束
            DataValidation validation = helper.createValidation(constraint, rangeList);
            // 阻止输入非下拉选项的值
            validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
            validation.setShowErrorBox(true);
            validation.setSuppressDropDownArrow(true);
            validation.createErrorBox("提示","此值与单元格定义格式不一致");
            // validation.createPromptBox("填写说明：","填写内容只能为下拉数据集中的单位，其他单位将会导致无法入仓");
            sheet.addValidationData(validation);
        });
    }

}
